<?php

	require_once "documentnode/DocumentNodeParser.php";
	require_once "googledocs/GoogleDocsLoader.php";
	require_once "documentnode/GoogleDocsNodeLoader.php";

	/**
	 * Handle publication of a google doc (or odt file).
	 */
	class GoogleDocsPublisher {

		private $target;
		private $template;
		private $odt;
		private $docId;
		private $publisher;
		private $document;

		/**
		 * Constructor.
		 */
		function GoogleDocPublisher() {
		}

		/**
		 * Set loader.
		 */
		function setPublisher($value) {
			$this->publisher=$value;
		}

		/**
		 * Set target.
		 */
		public function setTarget($value) {
			$this->target=$value;
		}

		/**
		 * Get target.
		 */
		public function getTarget() {
			return $this->target;
		}

		/**
		 * Set template.
		 */
		public function setTemplate($value) {
			$this->template=$value;
		}

		/**
		 * Set odt.
		 */
		public function setOdt($value) {
			$this->odt=$value;
		}

		/**
		 * Run the template.
		 */
		private function runTemplate($documentNode) {
			$document=$documentNode;

	        ob_start();
    	    require PathUtil::getScriptDir()."/".$this->template;
        	$contents = ob_get_contents();
        	ob_end_clean();

	        return $contents;
    	}

    	/**
    	 * Set google docs document id.
    	 */
    	public function setDocumentId($value) {
    		$this->docId=$value;
    	}

		/**
		 * Run the conversion.
		 */
		public function run() {
			$this->publisher->message("Processing Google Document: ".$this->template." -> ".$this->target);
			$parser=new DocumentNodeParser();

			if ($this->odt)
				$document=$parser->parseOdt($this->odt);

			else if ($this->docId) {
				$nodeLoader=new GoogleDocsNodeLoader();
				$nodeLoader->setParser($parser);
				$nodeLoader->setLoader($this->publisher->getGoogleDocsLoader());
				$document=$nodeLoader->loadDocumentNode($this->docId);
			}

			if (!$document)
				throw new Exception("Parse failed.");

			$output=$this->runTemplate($document);

			file_put_contents(PathUtil::getScriptDir()."/".$this->target, $output);

			foreach ($document->getUsedImages() as $used)
				$this->publisher->message("  Used image: ".$used);

			$this->document=$document;
		}

		/**
		 * Get used images.
		 */
		public function getUsedImages() {
			return $this->document->getUsedImages();
		}
	}